package com.example.token.interceptor;

import com.example.token.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class UserLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 在处理请求之前调用 (controller方法调用前)
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // return HandlerInterceptor.super.preHandle(request, response, handler);
        response.setCharacterEncoding("utf-8");
        String requestURI = request.getRequestURI();
        try {
            if (requestURI.contains("login")) {
                return true; // 放行
            }
            String token = request.getHeader("token");
            if (token == null) {
                log.error("请求头中没有token");
                response.getWriter().write("未登录,请先登录");
                return false;
            }
            if (!jwtUtil.validateToken(token)) {
                log.error("无效token,登录过期");
                response.getWriter().write("登录过期，请重新登录");
                return false;
            }
        } catch (Exception e) {
            System.out.println(e);
            return false;
        }
        return true; // 放行
    }

    /**
     * 请求处理之后调用，但在视图渲染前 (controller方法调用后)
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        System.out.println("执行了拦截器的postHandle方法");
    }

    /**
     * 整个请求结束后调用，即在DispatchServlet渲染了对应的视图后 (主要用于进行资源清理工作)
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        System.out.println("执行了拦截器的afterCompletion方法");
    }
}
